package com.changgou.seckill.mq.listener;

import com.alibaba.fastjson.JSON;
import com.changgou.seckill.mq.queue.QueueConfig;
import com.changgou.seckill.service.SeckillOrderService;
import com.github.wxpay.sdk.WXPayUtil;
import entity.HttpClient;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
@RabbitListener(queues = QueueConfig.QUEUE_MESSAGE)
public class DelayListener {

    @Autowired
    private SeckillOrderService seckillOrderService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${weixin.appid}")
    private String appid;

    @Value("${weixin.partner}")
    private String partner;

    @Value("${weixin.partnerkey}")
    private String partnerkey;

    /***
     * 监听消息
     * @param msg
     */
    @RabbitHandler
    public void msg(String msg) throws Exception {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("当前时间:"+dateFormat.format(new Date()));
        System.out.println("收到信息:"+msg);
        //将JSON数据转为SeckillStatus,获取用户排队信息
        Map<String,Object> seckillMap = JSON.parseObject(msg,Map.class);
//        SeckillStatus seckillStatus = new SeckillStatus("",123L,"");
        String outtradeno = seckillMap.get("orderId")+"";
        String username = (String) seckillMap.get("username");
        //查询redisz中是否有用户排队信息，如果有则订单还没有处理，没有则不管
        Object userSeckillQuery = redisTemplate.boundHashOps("UserSeckillQuery").get(username);
        if (userSeckillQuery != null){
            //关闭微信支付
            //取消订单
            //1.封装参数

            Map param = new HashMap();
            param.put("appid",appid);                            //应用ID
            param.put("mch_id",partner);                         //商户号
            param.put("out_trade_no",outtradeno);                //商户订单编号
            param.put("nonce_str", WXPayUtil.generateNonceStr()); //随机字符
            param.put("sign", "xiaohong");                        //签名

            //2、将参数转成xml字符，并携带签名
            String paramXml = null;

            paramXml = WXPayUtil.generateSignedXml(param,partnerkey);


            //3、发送请求
            HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/closeorder");
            httpClient.setHttps(true);
            httpClient.setXmlParam(paramXml);
            httpClient.post();

            //4、获取返回值，并将返回值转成Map
            String content = httpClient.getContent();
            Map<String, String> stringMap = WXPayUtil.xmlToMap(content);
            //判断关闭订单是否成功
            if (stringMap.get("return_code").equalsIgnoreCase("success")){
                //关闭订单成功
                //订单删除(逻辑删除)
                seckillOrderService.deletOrder(outtradeno,username);
            }else if (stringMap.get("return_code").equalsIgnoreCase("ORDERPAID")){
                //关闭订单失败 原因：已支付
                //查询支付状态并修改订单状态  out_trade_no
                HttpClient httpClient2 = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
                httpClient2.setHttps(true);
                httpClient2.setXmlParam(paramXml);
                httpClient2.post();
                //获取返回值，并将返回值转成Map
                String content2 = httpClient.getContent();
                Map<String, String> stringMap2 = WXPayUtil.xmlToMap(content2);
                seckillOrderService.updateStatus(outtradeno,stringMap2.get("transaction_id"),stringMap2.get("time_end"),username);
            }else {
                //关闭订单失败 原因：其他错误
                //订单回滚(逻辑删除)
                seckillOrderService.deletOrder(outtradeno,username);
            }
        }
    }

}